package com.joysuch.wwyt.risk.controller;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.entity.bean.BpRecordItemBean;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.repeatsubmit.NoRepeatSubmit;
import com.joysuch.wwyt.risk.bean.*;
import com.joysuch.wwyt.risk.entity.RiskEvaluationBusiness;
import com.joysuch.wwyt.risk.entity.RiskPointEvaluationBusiness;
import com.joysuch.wwyt.risk.entity.vo.RiskEvaluationRecordDeleteCheckVO;
import com.joysuch.wwyt.risk.entity.vo.RiskItemEvalCountRecordVo;
import com.joysuch.wwyt.risk.service.RiskEvaluationBusinessService;
import com.joysuch.wwyt.risk.service.RiskEvaluationExcelImportService;
import com.joysuch.wwyt.risk.service.RiskStorePointEvalExcelExportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/risk/evaluation")
@Api(tags = "双预防-风险评估")
@Slf4j
public class RiskEvaluationBusinessController {

    @Autowired
    private RiskEvaluationBusinessService service;
    @Autowired
    private RiskEvaluationExcelImportService importService;
    @Autowired
    private RiskStorePointEvalExcelExportService exportService;

    @GetMapping("pageRiskDistrictEvaluation")
    @ApiOperation("获取风险分区评估列表")
    public Object stableRiskList(Pageable page, RiskDistrictStableRiskListSearchBean condition) {
        page = PageDataUtils.addOrderByDesc(page, "createTime");
        Page<RiskEvaluationBusinessPageBean> pageData = service.pageRiskDistrictEvaluation(page, condition);
        return ResultBean.pageData(pageData.getContent(), pageData.getTotalElements());
    }

    @GetMapping("getDistEvalNum")
    @ApiOperation("获取已评估风险分区数量")
    public ResultBean getDistEvalNum() {
        return ResultBean.success(service.getDistEvalNum());
    }

    @PostMapping("saveBusiness")
    @ApiOperation("保存风险评估")
    @RequiresPermissions("risk:evaluation:saveBusiness")
    public ResultBean saveBusinessEvalustion(@RequestBody RiskEvaluationBusinessBean bean) {
        RiskEvaluationBusiness reb = service.saveBusiness(bean);
        return ResultBean.success(reb);
    }

    @GetMapping("getBusinessById")
    @ApiOperation("查看风险评估")
    public ResultBean getBusinessById(Long riskDistrictId) {
        RiskEvaluationBusinessShowBean bean = service.getBusinessById(riskDistrictId);
        return ResultBean.success(bean);
    }

    @GetMapping("getPointInDistrictList")
    @ApiOperation("获取风险分区风险点列表")
    public ResultBean stableRiskList(Long riskDistrictId, Pageable page) {
        Page<RiskPointOfDistrictListBean> data = service.getPointInDistrictList(riskDistrictId, page);
        return ResultBean.pageData(data.getContent(), data.getTotalElements());
    }

    @PostMapping("savePointEvaluation")
    @ApiOperation("保存风险点风险评估：作业分析库")
    public ResultBean savePointEvaluation(@RequestBody RiskPointEvaluationBusinessBean bean) {
        RiskPointEvaluationBusiness pb = service.savePointEvaluation(bean);
        return ResultBean.success(pb);
    }

    @PostMapping("savePointEvaluationForRiskAssessment")
    @ApiOperation("保存风险点风险评估：风险评估")
    @NoRepeatSubmit(paramNames = "pointId,analyzeWayId")
    public ResultBean savePointEvaluationForAssessment(@RequestBody RiskPointEvaluationBusinessBean bean) {
        RiskPointEvaluationBusiness pb = null;
        try {
            pb = service.savePointEvaluationForAssessment(bean);
        } catch (BusinessRestrictionsException e) {
            return ResultBean.fail(Status.HAS_SAME_CONTROL_MEASURES_AND_CONTENT.getCode(), e.getMessage());
        }
        return ResultBean.success(pb);
    }

    @GetMapping("getPointEvaluation")
    @ApiOperation("查看风险点风险评估：作业分析库")
    public ResultBean getPointEvaluation(Long riskPointId, Integer pointAnalyzeType, Long analyzeWayId, Long riskEvaluationId) {
        RiskPointEvaluationBusinessShowBean bean = service.getPointEvaluation(riskPointId, pointAnalyzeType, analyzeWayId, riskEvaluationId);
        return ResultBean.success(bean);
    }

    @GetMapping("getPointEvaluationForRiskAssessment")
    @ApiOperation("查看风险点风险评估：风险评估")
    public ResultBean getPointEvaluationForAssessment(Long riskPointId, Long analyzeWayId, Long riskEvaluationId) {
        RiskPointEvaluationBusinessShowBean bean = service.getPointEvaluationForAssessment(riskPointId, analyzeWayId, riskEvaluationId);
        return ResultBean.success(bean);
    }

    @GetMapping("getPointHistoryEvaluationData")
    @ApiOperation("查看风险点评估历史记录")
    public ResultBean getPointHistoryEvaluationData(Long riskPointId, Pageable page) {
        return service.getPointHistoryEvaluationData(riskPointId, page);
    }

    @GetMapping("deleteByPointEvaluationId")
    @ApiOperation("删除风险点历史记录")
    public ResultBean deleteByPointEvaluationId(Long riskPointEvaluationId) {
        try {
            service.deleteByPointEvaluationId(riskPointEvaluationId);
        } catch (ApiBusinessException e) {
            if (e.getCode() == Status.DELETE_CHECK_FAILED.getCode() && StringUtils.isNotEmpty(e.getMessage())) {
                List<RiskEvaluationRecordDeleteCheckVO> vos = JSONObject.parseArray(e.getMessage(), RiskEvaluationRecordDeleteCheckVO.class);
                return ResultBean.fail(e.getCode(), "", vos);
            } else {
                return ResultBean.fail(101, e.getMessage());
            }
        }
        return ResultBean.success("");
    }

    @GetMapping("pagePoint")
    @ApiOperation("管控-监测点分页")
    public ResultBean getPointEvaluation(Pageable pageable, RiskControlSearchBean condition) {
        Page<RiskControPointBean> page = service.pageControlList(pageable, condition);
        return ResultBean.pageData(page.getContent(), page.getTotalElements());
    }

    @GetMapping("pagePointEvaluationDetail")
    @ApiOperation("管控-措施分页")
    public ResultBean pagePointEvaluationDetail(Pageable pageable, RiskControlSearchBean condition, Long pointId) {
        return ResultBean.success(service.pagePointEvaluationDetail(pageable, condition, pointId));
    }


    @GetMapping("getPointEvaluationDetail")
    @ApiOperation("风险点详情")
    public ResultBean getPointEvaluationDetail(Pageable pageable, Long pointId) {
        RiskPointEvalBean bean = service.getPointEvaluationDetail(pageable, pointId);
        return ResultBean.success(bean);
    }


    @GetMapping("riskControlDetailedList")
    @ApiOperation("风险分级管控-清单字段列表")
    public ResultBean getRiskControlDetailedList(Long pointId) {
        RiskControlDetailed bean = service.getRiskControlDetailedList(pointId);
        return ResultBean.success(bean);
    }

    @PostMapping("saveControl")
    @ApiOperation("保存分级管控")
    @RequiresPermissions("risk:evaluation:saveControl")
    public ResultBean saveControl(@RequestBody RiskPointControlBean bean) {
        return ResultBean.success(service.saveControl(bean));
    }

    @PostMapping("saveListControl")
    @ApiOperation("批量分级管控")
    @RequiresPermissions("risk:evaluation:saveListControl")
    public ResultBean saveListControl(@RequestBody RiskPointControlBean bean) {
        service.saveListControl(bean);
        return ResultBean.defaultSuccessResult();
    }

    @GetMapping("pageControlPointDetail")
    @ApiOperation("管控-排查措施分页")
    @Qualifier
    public ResultBean pagelScreenPointDetail(Pageable pageable, RiskControlSearchBean condition) {
        List<Integer> controlStateList = new ArrayList<>();
        controlStateList.add(2);
        condition.setControlStateList(controlStateList);
        return service.pageControlPointDetail(pageable, condition);
    }

    @GetMapping("pageScreenPointDetails")
    @ApiOperation("管控-大屏措施分页")
    @Qualifier
    public ResultBean pageControlPointDetails(Pageable pageable, Long districtId) {
        RiskControlSearchBean condition = new RiskControlSearchBean();
        List<Integer> controlStateList = new ArrayList<>();
        controlStateList.add(1);
        controlStateList.add(2);
        controlStateList.add(3);
        condition.setControlStateList(controlStateList);
        condition.setDistrictId(districtId);
        return service.pageScreenPointDetails(pageable, condition);
    }

    @GetMapping("getControlLevelList")
    @ApiOperation("获取管控层级列表")
    public ResultBean getControlLevelList() {
        List<SimpleSelectListBean> list = service.getControlLevelList();
        return ResultBean.success(list);
    }


    @GetMapping("getControlStateList")
    @ApiOperation("获取管控状态列表")
    public ResultBean getControlStateList() {
        List<SimpleSelectListBean> list = service.getControlStateList();
        return ResultBean.success(list);
    }

    @GetMapping("exportDistrictEvaluationExcel")
    @ApiOperation("区域风险评估数据/模板导出")
    @RequiresPermissions("risk:evaluation:districtEvaluationExcel")
    public ResultBean exportDistrictEvaluationExcel(HttpServletResponse response, Integer isTemplate, Integer shared, String districtIds) {
        try {
            SXSSFWorkbook workBook = exportService.exportDistrictEvaluationExcel(isTemplate, shared, districtIds);
            ServletOutputStream outputStream = response.getOutputStream();
            String name =this.getTemplateName(shared,isTemplate);
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
            workBook.write(outputStream);
            outputStream.close();
            return ResultBean.success("下载成功...... ");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.fail(101, "下载失败:" + e.getMessage());
        }
    }

    private String getTemplateName(Integer shared, Integer isTemplate) {
        String name ="";
        if (shared == null || shared == 0) {
            name = "05_风险评估数据导出.xlsx";
            if (isTemplate==0){
                name = "05_风险评估导入模板.xlsx";
            }
        }else{
             name = "21_作业分析库数据导出.xlsx";
             if (isTemplate==0){
                 name = "21_作业分析库导入模板.xlsx";
             }
        }
        return name;
    }

    //2.11.1 错误信息下载是前段完成的 未调用后端接口
    @Deprecated
    @PostMapping("exportEvalErrorMessages")
    @ApiOperation("错误信息下载")
    public void exportEvalErrorMessages(@RequestBody RiskEvalMessageBean bean, HttpServletResponse response) {
        exportService.exportEvalErrorMessages(bean.getErrorMessages(), response);
    }

    @PostMapping("editDistrictEvaluation")
    @ApiOperation("修改风险评估等级")
    public ResultBean importDistrictEvaluationExcel(@RequestBody RiskEditDistrictEvaluationBean bean) {
        RiskDistrictEvalBean evalBean = service.editDistrictEvaluation(bean);
        return ResultBean.success(evalBean);
    }

    @PostMapping("importDistrictEvaluationExcel")
    @ApiOperation("区域风险评估数据导入")
    @RequiresPermissions("risk:evaluation:districtEvaluationExcel")
    public ResultBean importDistrictEvaluationExcel(MultipartFile file, Integer shared) {
        List<String> errorMessage = null;
        try {
            if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
                return ResultBean.success(Lists.newArrayList("文件类型不正确"));
            }
            errorMessage = importService.importDistrictEvaluationExcel(file, shared);
            return ResultBean.success(errorMessage);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.success(Lists.newArrayList("导入失败:" + e.getMessage()));
        }

    }

    @GetMapping("riskPointControlPrint")
    @ApiOperation("获取风险点评估json数据")
    public ResultBean getRiskPointEvaluationJson(Long riskPointId, Long riskPointEvaluationId, Long workSafetyDistrictId) {
        return service.getRiskPointEvaluationJson(riskPointId, riskPointEvaluationId, workSafetyDistrictId);
    }

    @GetMapping("getRiskPointControl")
    @ApiOperation("获取风险管控数据")
    public ResultBean getRiskPointControl(RiskControlSearchBean searchBean, Long riskPointId) {
        return service.getRiskPointControl(searchBean, riskPointId);
    }

    @GetMapping("getRiskPointControlForScreenPage")
    @ApiModelProperty("大屏风险管控清单")
    public ResultBean getRiskPointControlForScreenPage(RiskControlSearchBean searchBean) {
        return service.getRiskPointControlForScreenPage(searchBean);
    }


    @GetMapping("recalculateRealRiskLevel")
    @ApiModelProperty("实时值重新计算")
    public ResultBean recalculateRealRiskLevel(Long itemId, Integer flag) {
        service.recalculateRealRiskLevel(flag, new RiskItemEvalCountRecordVo("test", "recalculateRealRiskLevel", itemId));
        return ResultBean.success("");
    }

    @GetMapping("convertUnCheckedRealRiskLevel")
    @ApiModelProperty("未检")
    public ResultBean convertUnCheckedRealRiskLevel(Long itemId, Long planId, Long evalItemId) {
        List<BpRecordItemBean> uncheckedBeanList = new ArrayList<>();
        BpRecordItemBean itemBean = new BpRecordItemBean(itemId, planId, evalItemId);
        uncheckedBeanList.add(itemBean);
        service.convertUnCheckedRealRiskLevel(uncheckedBeanList);
        return ResultBean.success("");
    }

    @GetMapping("convertCheckedRealRiskLevel")
    @ApiModelProperty("已检")
    public ResultBean convertCheckedRealRiskLevel(Long itemId, Long planId) {
        Map<Long, List<Long>> itemPlanMap = new HashMap<>();
        itemPlanMap.put(itemId, Lists.newArrayList(planId));
        service.convertCheckedRealRiskLevel(itemPlanMap, "convertCheckedRealRiskLevel");
        return ResultBean.success("");
    }

}
